<template>
	<view class="">
		<!-- Header -->
		<view class="header bg-white">
			<u-search placeholder="输入商品名称" @change="change(current)" :show-action="false" v-model="keyword"></u-search>
		</view>

		<!-- Nav -->
		<view class="nav bg-white">
			<u-tabs name="name" :show-bar="false" :list="list" :is-scroll="true" :current="current" count="cate_count"
				@change="change" active-color="#40AFFA" />
		</view>

		<!-- Section -->
		<view class="section" :style="{'height': height}">
			<swiper :duration="400" style="height: 100%; overflow: hidden;" @change="change" :current="current">
				<swiper-item v-for="(items, index) in list" :key="index">
					<!-- 商品发布 -->
					<view class="public-produts" v-show="index == 0">
						<!-- <mescroll-uni ref="mescrollRef" bottom="220rpx" height="100%"> -->
						<view class="code-view">
							<image @click="scanCodeEvent" class="code-img" src="@/static/images/verification.png"
								mode=""></image>
							<text @click="scanCodeEvent">扫码上架</text>
						</view>
						<view class="form-view">
							<view class="item bb">
								<view>商品条码: </view>
								<view class="flex row-between g-input">
									<input type="text" placeholder="请输入商品条码" v-model="pruductForm.code" />
								</view>
							</view>
							<view class="item bb">
								<view>商品标题: </view>
								<view class="flex row-between g-input">
									<input type="text" placeholder="请输入商品标题" v-model="pruductForm.name" />
								</view>
							</view>
							<view class="item bb">
								<view>商品图片: </view>
								<view class="flex upload-style">
									<u-upload name="file" :show-progress='false'
										:action="baseUrl + '/shopapi/goods/upload_image'" :header="header"
										:file-list="fileList1" @on-success="onSuccess" multiple :maxCount="1"
										width="250" height="150">
										<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png"
											mode="widthFix" style="width: 250px;height: 150px;"></image>
									</u-upload>
								</view>
							</view>
							<view class="spec-view">
								<u-collapse>
									<u-collapse-item title="商品规格" name="spec" v-if="pruductForm.items">
										<view class="item bb">
											<view>规格图片: </view>
											<view class="flex upload-style">
												<u-upload name="file" :show-progress='false'
													:action="baseUrl + '/shopapi/goods/upload_image'" :header="header"
													:file-list="fileList2" @on-success="onSuccess1" multiple
													:maxCount="1" width="250" height="150">
													<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png"
														mode="widthFix" style="width: 250px;height: 150px;"></image>
												</u-upload>
											</view>
										</view>
										<view class="item bb">
											<view>市场价(元): </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入市场价"
													v-model="pruductForm.items[0].market_price" />
											</view>
										</view>
										<view class="item bb">
											<view>价格(元): </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入价格"
													v-model="pruductForm.items[0].price" />
											</view>
										</view>
										<view class="item bb">
											<view>成本价(元): </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入成本价"
													v-model="pruductForm.items[0].chengben_price" />
											</view>
										</view>
										<view class="item bb">
											<view>库存: </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入库存"
													v-model="pruductForm.items[0].stock" />
											</view>
										</view>
										<view class="item bb">
											<view>重量(kg): </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入重量"
													v-model="pruductForm.items[0].weight" />
											</view>
										</view>
										<view class="item bb">
											<view>体积(m3): </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入体积"
													v-model="pruductForm.items[0].volume" />
											</view>
										</view>
										<view class="item bb">
											<view>条码: </view>
											<view class="flex row-between g-input">
												<input type="text" placeholder="请输入条码"
													v-model="pruductForm.items[0].bar_code" />
											</view>
										</view>
									</u-collapse-item>
								</u-collapse>
							</view>

							<view class="public-view">
								<view class="public-btn" @click="pushProEvent">上 架</view>
							</view>
						</view>
						<!-- </mescroll-uni> -->
					</view>
					<view v-show="index == current && index != 0">
						<mescroll-uni ref="mescrollRef" bottom="220rpx" height="100%" @init="mescrollInit"
							@up="upCallback" :up="upOption" @down="downCallback">

							<view class="title muted sm">
								共{{ count }}件商品
							</view>

							<block v-for="(item2, index2) in items.lists" :key="index2">
								<goods-card :data="item2">
									<template v-if="btns.recycle_btn">
										<button class="btn hollow br60 flex row-center normal"
											@click="openFunc(item2, 'recycle')">移至回收站</button>
									</template>
									<template v-if="btns.edit_btn">
										<router-link :to="'/bundle/pages/spec_edit/spec_edit?id='+item2.id">
											<button class="btn hollow br60 flex row-center normal">编辑</button>
										</router-link>
									</template>
									<template v-if="btns.delete_btn">
										<button class="btn hollow br60 flex row-center normal"
											@click.stop="openFunc(item2, 'del')">删除</button>
									</template>
									<template v-if="current==1">
										<button class="btn solid br60 flex row-center normal"
											@click.stop="openFunc(item2, 'off_shelf')">下架</button>
									</template>
									<template v-if="current==2">
										<button class="btn solid br60 flex row-center normal"
											@click.stop="openFunc(item2, 'on_shelf')"
											style="background: #40AFFA;">上架</button>
									</template>
									<template v-if="btns.warehouse_btn">
										<button class="btn solid br60 flex row-center normal"
											@click.stop="openFunc(item2, 'warehouse')"
											style="background: #40AFFA;">放入仓库</button>
									</template>
								</goods-card>
							</block>

						</mescroll-uni>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<modal height="200rpx" v-model="off_shelf" @confirm="goodsSetting">
			<view class="black nr" style="height: 200rpx;">
				确认下架：<text style="color:#FF4141;">{{curData.name}}</text>
			</view>
		</modal>

		<modal height="200rpx" v-model="on_shelf" @confirm="goodsSetting">
			<view class="black nr" style="height: 200rpx;">
				确认上架：<text style="color:#FF4141;">{{curData.name}}</text>
			</view>
		</modal>

		<modal height="200rpx" v-model="del" @confirm="goodsSetting">
			<view class="black nr" style="height: 200rpx;">
				确认删除：<text style="color:#FF4141;">{{curData.name}}</text>
			</view>
		</modal>

		<modal height="200rpx" v-model="recycle" @confirm="goodsSetting">
			<view class="black nr" style="height: 200rpx;">
				确认移至回收站：<text style="color:#FF4141;">{{curData.name}}</text>
			</view>
		</modal>

		<modal height="200rpx" v-model="warehouse" @confirm="goodsSetting">
			<view class="black nr" style="height: 200rpx;">
				确认放入仓库：<text style="color:#FF4141;">{{curData.name}}</text>
			</view>
		</modal>

		<u-toast ref="uToast" />
		<tabBar :currentPagePath="path"></tabBar>
	</view>
</template>


<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import {
		apiGoodsLists,
		apiGoodsOperation,
		apiGoodsBars,
		apiGoodsDetailbycode,
		apiGoodsEdit
	} from '@/api/goods'
	import {
		baseURL
	} from '@/config/app'
	import {
		debounce
	} from "@/utils/tools.js"
	import store from '@/store'

	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				isShowUpload: true,
				baseUrl: '',
				header: {
					token: store.getters.token || '',
				},
				path: '', //页面路径
				height: '100%',

				pruductForm: {
					name: "",
					code: "",
					goods_image: [],
					items: [{
						image: "",
						id: '',
						market_price: "", //市场价
						price: "",
						stock: "",
						chengben_price: "", //成本价
						weight: '', //重量
						volume: '', //体积
						bar_code: '', //条码
					}],
					action: "on_shelf", //上架
				}, //发布商品
				fileList1: [],
				fileList2: [],

				keyword: '',
				list: [{
						name: '发布商品',
						type: 0,
						cate_count: 0,
						lists: []
					},
					{
						name: '销售中',
						type: 1,
						cate_count: 0,
						lists: []
					},
					{
						name: '仓库中',
						type: 2,
						cate_count: 0,
						lists: []
					},
					{
						name: '库存预警',
						type: 3,
						cate_count: 0,
						lists: []
					},
					{
						name: '回收站',
						type: 4,
						cate_count: 0,
						lists: []
					},
					{
						name: '待审核',
						type: 5,
						cate_count: 0,
						lists: []
					},
					{
						name: '未通过',
						type: 6,
						cate_count: 0,
						lists: []
					}
				],
				current: 0,
				count: 0,

				action: '',
				curData: {},

				btns: {},

				off_shelf: false, //下架
				on_shelf: false, // 上架
				del: false, //删除
				recycle: false, //回收站
				warehouse: false, //放入仓库

				upOption: {
					empty: {
						icon: '/static/images/empty/shop.png',
						tip: '暂无商品！', // 提示
						fixed: true,
						top: "200rpx",
					}
				}
			}
		},
		onLoad() {
			var pages = getCurrentPages()
			this.path = pages[pages.length - 1].route

			this.getAllCount()

			this.baseUrl = baseURL
			console.log(this.baseUrl, '-----')
		},
		async onShow() {
			// 使用防抖是为了防止v-show的时候出发多条数据，所以使用防抖触发多次的时候可以只成为触发一次，优化性能请求
			this.upCallback = debounce(this.upCallback, 200, this)
			this.$nextTick(() => {
				this.$refs.mescrollRef[this.current].mescroll.resetUpScroll()
			})

			uni.getSystemInfo({
				success: (res) => {
					this.height = res.windowHeight - 107 + 'px';
				}
			});
		},

		methods: {
			//获取状态条数量
			getbarsNum() {
				apiGoodsBars().then(res => {
					this.list.forEach((item) => {
						res.list.forEach(item2 => {
							if (item.type == item2.type) {
								item.cate_count = item2.count
							}
						})
					})
					this.list[0].cate_count = 0 // 商品发布
					this.list = [...this.list]
				})
			},
			// 扫码
			scanCodeEvent() {
				// 调起条码扫描
				uni.scanCode({
					scanType: ['barCode'],
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						apiGoodsDetailbycode({
							goods_code: res.result, // '26966981'
						}).then(res => {
							console.log("扫码结果")
							console.log(res)
							this.pruductForm.code = res.code
							this.pruductForm.name = res.name
							this.pruductForm.goods_image.push(res.image)
							//规格
							this.pruductForm.items[0].image = res.goods_item[0].image
							this.pruductForm.items[0].id = res.goods_item[0].id
							this.pruductForm.items[0].market_price = res.goods_item[0].market_price
							this.pruductForm.items[0].price = res.goods_item[0].price
							this.pruductForm.items[0].stock = res.goods_item[0].stock
							this.pruductForm.items[0].chengben_price = res.goods_item[0].chengben_price
							this.pruductForm.items[0].weight = res.goods_item[0].weight
							this.pruductForm.items[0].volume = res.goods_item[0].volume
							this.pruductForm.items[0].bar_code = res.goods_item[0].bar_code
							// this.pruductForm.items[0].spec_value_ids = res.goods_item[0].spec_value_ids //规格id
							// this.pruductForm.items[0].spec_value_str = res.goods_item[0].spec_value_str //规格名称
							// this.pruductForm.items[0].goods_id = res.goods_item[0].goods_id //商品id

							this.fileList1 = [{
								url: res.image
							}]
							this.fileList2 = [{
								url: res.goods_item[0].image
							}]

							this.pruductForm = {
								...this.pruductForm
							}
						})
					}
				});
			},
			onSuccess(data) {
				this.pruductForm.goods_image.push(data.data.uri)
			},
			onSuccess1(data) {
				this.pruductForm.items[0].image = data.data.uri
			},
			// 上架
			pushProEvent() {
				// 表单校验
				if (!this.pruductForm.code) {
					this.$refs.uToast.show({
						title: '请输入商品条码',
						type: 'none'
					})
					return
				} else if (!this.pruductForm.name) {
					this.$refs.uToast.show({
						title: '请输入商品标题',
						type: 'none'
					})
					return
				} else if (this.pruductForm.goods_image.length == 0) {
					this.$refs.uToast.show({
						title: '请添加商品图片',
						type: 'none'
					})
					return
				}else if (this.pruductForm.items[0].image.length == 0) {
					this.$refs.uToast.show({
						title: '请添加商品规格图片',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].market_price){
					this.$refs.uToast.show({
						title: '请输入市场价',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].price){
					this.$refs.uToast.show({
						title: '请输入价格',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].chengben_price){
					this.$refs.uToast.show({
						title: '请输入成本价',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].stock){
					this.$refs.uToast.show({
						title: '请输入库存',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].weight){
					this.$refs.uToast.show({
						title: '请输入重量',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].volume){
					this.$refs.uToast.show({
						title: '请输入体积',
						type: 'none'
					})
					return
				}else if(!this.pruductForm.items[0].bar_code){
					this.$refs.uToast.show({
						title: '请输入条码',
						type: 'none'
					})
					return
				}
				let that = this
				apiGoodsEdit(this.pruductForm).then(res => {

					this.$refs.uToast.show({
						title: '上架成功',
						type: 'success'
					})

					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/goods_manage/goods_manage'
						})
					}, 1500)
				})
			},

			change(event) {
				let index;
				event.detail ? index = event.detail.current : index = event
				this.current = Number(index)
				this.$refs.mescrollRef[this.current].mescroll.resetUpScroll()
			},
			getAllCount() {
				console.log('all')
				apiGoodsLists({
					name: this.keyword,
					type: '',
					page_no: 1,
					page_size: 10,
				}).then(({
					count,
				}) => {
					this.count = count;
					// this.list[index].cate_count = count
				}).catch((err) => {
					console.log(err)
					this.mescroll.endErr()
				})
			},

			async upCallback(page) {
				const index = this.current;
				const pageNum = page.num
				const pageSize = page.size

				this.getbarsNum()

				apiGoodsLists({
					name: this.keyword,
					type: this.list[index].type,
					page_no: pageNum,
					page_size: pageSize,
				}).then(({
					lists,
					page_size,
					btns,
					more,
					count,
				}) => {
					// 如果是第一页需手动置空列表
					if (pageNum == 1 || this.keyword) this.list[index].lists = []
					// 重置列表数据
					this.btns = btns;
					this.count = count;
					this.list[index].cate_count = count
					this.list[0].cate_count = 0
					const hasNext = !!more;
					this.list[index].lists = [...this.list[index].lists, ...lists]
					this.$refs.mescrollRef[index].mescroll.endSuccess(lists.length, hasNext);
				}).catch((err) => {
					console.log(err)
					this.mescroll.endErr()
				})
			},

			openFunc(item, action) {
				this.curData = item;
				this.action = action;
				this[action] = true;
			},

			// 操作商品
			async goodsSetting() {
				let id = this.curData.id,
					action = this.action == 'del' ? 'delete' : this.action
				await apiGoodsOperation({
					action,
					id
				})

				this.$refs.mescrollRef[this.current].mescroll.resetUpScroll()
				this.$refs.uToast.show({
					title: '操作成功',
					type: 'success'
				})
			}
		}
	}
</script>


<style lang="scss">
	/*根元素需要有固定的高度*/
	page {
		height: 100%;
		box-sizing: border-box;

		.header {
			padding: 16rpx 30rpx;
		}

		.nav {
			padding: 15rpx 0;
		}

		.section {
			overflow: hidden;

			.title {
				padding: 20rpx;
			}

			.btn {
				margin-top: 20rpx;
				margin-left: 20rpx;
				width: 180rpx;
				height: 64rpx;
				// border-radius: 8rpx;
				font-size: $-font-size-sm;
			}

			.solid {
				color: $-color-white;
				background-color: #FF4141;
			}

			.hollow {
				color: $-color-lighter;
				border: 1px solid #DBDBDB;
			}
		}

		.public-produts {
			height: 100%;
			overflow-y: scroll;
			background: #ffffff;

			.code-view {
				padding: 5px 20px;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				margin-top: 10px;

				.code-img {
					width: 32px;
					height: 32px;
					cursor: pointer;
				}
			}

			.item {
				padding: 30rpx;
				/* #ifndef APP-NVUE */
				display: flex;
				/* #endif */
				flex-direction: row;
				align-items: center;
				background-color: $-color-white;
				justify-content: flex-start;

				.upload-style {
					height: 75px !important;
				}

				>view:first-child {
					width: 180rpx;
					color: $-color-black;
					font-size: $-font-size-nr;
					font-weight: 500;
				}

				.g-input {
					border: 1px solid rgba(219, 219, 219, 100);
				}

				>view:last-child {
					width: 500rpx;
					text-align: left;
					height: 76rpx;
					padding: 0 12rpx;
					border-radius: 6rpx;

					uni-input {
						width: 100%;
					}
				}
			}

			// 商品规格
			.spec-view {
				padding: 0 15px;
				// .spec-title {
				// 	padding: 0 0 0 15px;
				// }
			}

			.public-view {
				padding: 10px 0 20px 0;

				.public-btn {
					width: 90%;
					margin: 0 auto;
					background: #40AFFA;
					text-align: center;
					padding: 25rpx 0;
					color: #ffffff;
					border-radius: 18px;
				}
			}
		}
	}
</style>